package com.dream.myqiyi;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoader {
	// 为了加快速度，在内存中开启缓存（主要应用于重复图片较多时，或者同一个图片要多次被访问，比如在ListView时来回滚动）
	public Map<String,SoftReference<Drawable>> imageCache;
	
	public AsyncImageLoader(){
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}
	
	public Drawable loadDrawable(final String imageUrl, final int width, final int height, final ImageCallback imageCallback) {
		// 判断是否有缓存的图片，有的话返回缓存，没得话开启线程下载 
        if (imageCache.containsKey(imageUrl)) {
        	// 有的情况 
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = softReference.get();
            // 返回缓存图片 
            if (drawable != null) {
                return drawable;
            }
        }
      // 没的情况 
        final Handler handler = new Handler() {
            @Override
			public void handleMessage(Message message) {
            	if (imageCallback != null) {
            		imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
            	}                
            }
        };
        new Thread() {
            @Override
            public void run() {
            	// 下载图片
                Drawable drawable = loadImageFromDb(imageUrl, width, height);
                int count = 0;
                while (drawable == null && count < 10) {
                	try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                	drawable = loadImageFromDb(imageUrl, width, height);
                }
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }.start();
        return null;
    }
 
	// 根据图片网络地址返回一个Drawable 
	public static Drawable loadImageFromUrl(String url) {
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Drawable d = null;
		if (i != null) {
			d = Drawable.createFromStream(i, "src");
		}
		return d;
	}
	
	public static Drawable loadImageFromDb(String guid, int width, int height) {
		Drawable d = null;
		try { 
			d = Global.getImageResource(guid, width, height);
		} catch (OutOfMemoryError e) { 
		}
		return d;
	}
 
    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }
    
    public void removeCache(String url) {
    	imageCache.remove(url);
    }

}
